import { useState, useEffect } from 'react';
import { handleApiResponse } from './domUtils';

interface SystemConfig {
  sdWebUI: {
    baseUrl: string;
    defaultPort: number;
  };
  api: {
    baseUrl: string;
    timeout: number;
  };
  version: string;
  title: string;
}

export const useConfig = () => {
  const [config, setConfig] = useState<SystemConfig | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchConfig = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/config');
        
        const data = await handleApiResponse(response);
        setConfig(data);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
        console.error('Failed to load configuration:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchConfig();
  }, []);

  return { config, loading, error };
};
